package com.accp.action;

import java.util.List;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import com.opensymphony.xwork2.ActionContext;

public class MyAction {
	// 公共消息
	public static String toMsg(String msg, String url) {
		ActionContext.getContext().put("msg", msg);
		ActionContext.getContext().put("url", url);
		return "msg";
	}
	public static String toAjax(Object obj){
		String json="";
		if(obj instanceof String){
			json=obj.toString();
		}else if(obj instanceof List){
			json=listToJson(obj);
		}else{
			json=objToJson(obj);
		}
		ActionContext.getContext().put("data",json);
		return "ajax";
	}
	
	private static String objToJson(Object obj) {
		try {
			return JSONUtil.serialize(obj);
		} catch (JSONException e) {
			e.printStackTrace();
			return "{}";
		}
	}
	private static String listToJson(Object obj) {		
		try {
			return JSONUtil.serialize(obj);
		} catch (JSONException e) {
			e.printStackTrace();
			return "[]";
		}
	}
	// 保存数据到Session
	public static void saveSession(String key, Object value) {
		ActionContext.getContext().getSession().put(key, value);
	}

	// 从Session取数据
	public static Object getSession(String key) {
		return ActionContext.getContext().getSession().get(key);
	}

	// 从Session删除数据
	public static void removeSession(String key) {
		ActionContext.getContext().getSession().remove(key);
	}
}
